<template>
  <div class="edit-draft bg-hex-fff">
    <!-- 顶部 -->
    <div class="h-200rpx" />
    <div class="fixed left-0 right-0 top-0 z-9 h-200rpx bg-hex-ffffff">
      <image class="pointer-events-none absolute left-0 right-0 top-0 w-full" :src="`${cdnUrl}/imgs/detail/bg.png${imgVersion}`"
             mode="aspectFill" />
      <div
        class="z-999 inline-block w-24% flex items-center pb-40rpx"
        :style="{ paddingTop: `${searchBarTop}px` }"
        @click.stop="goBack">
        <uni-icons type="back" size="28" />
        <text class="text-36rpx font-600">返回</text>
      </div>
    </div>
    <!-- 底部tab栏 -->
    <!-- 发动态 -->
    <div v-if="tabindex==='0'">
      <div class="box-border px-32rpx pb-370rpx">
        <div class="flex flex-wrap">
          <div v-for="(item, index) in fileLists"
               class="relative mb-25rpx mr-25rpx flex flex-col items-center justify-center rounded-20rpx bg-hex-F5F5F5">
            <image
              class="h-152rpx w-152rpx flex flex-col items-center justify-center rounded-20rpx bg-hex-F5F5F5"
              :src="item"
              mode="scaleToFill"
              @click="previewImage(index)"
            />
            <div
              class="absolute h-40rpx w-40rpx flex items-center justify-center border rounded-50% bg-[rgba(0,0,0,0.7)] -bottom-18rpx -right-18rpx"
              @click.stop="deleteImg(index)">
              <image
                class="h-40rpx w-40rpx"
                :src="`${cdnUrl}/imgs/mine/close.png${imgVersion}`"
                mode="scaleToFill"
              />
            </div>
          </div>
          <div class="mb-20rpx h-152rpx w-152rpx flex flex-col items-center justify-center rounded-20rpx bg-hex-F5F5F5"
               @click="select">
            <uni-icons type="plusempty" size="30" color="#D9D9D9" />
          </div>
        </div>
        <!-- </uni-file-picker> -->
        <div class="max-h-600rpx overflow-y-scroll">
          <uni-easyinput v-model="dynamicContent" :inputBorder="false" maxlength="120"
                         autoHeight type="textarea"
                         placeholderStyle="color:#C4C4C4;font-size:32rpx"
                         placeholder="快来写下当前的动态,让更多人看到吧~" />
        </div>
        <div class="tablist fixed bottom-200rpx left-0 right-0 z-99 h-102rpx bg-hex-FFFFFF px-32rpx" :class="{ 'bottom-520rpx': isShowColumn }">
          <div class="mb-24rpx flex items-center justify-between text-28rpx text-hex-7C8699" @click="handleShowColumn">
            <div>{{ columnName }}</div>
            <uni-icons :type="isShowColumn?'top':'bottom'" size="16" />
          </div>
          <div v-if="isShowColumn" class="columns mb-32rpx box-border max-h-350rpx overflow-y-auto rounded-30rpx bg-hex-F6F6F6 p-32rpx">
            <div v-for="item in categoryList" class="mb-32rpx text-28rpx text-hex-7c8699"
                 :class="columnName===item.name ? 'text-hex-000000 font-700 text-34rpx':''"
                 @click="changecolumnId(item)">{{ item.name }}</div>
          </div>
        </div>
        <div class="fixed bottom-30rpx left-0 right-0 z-99 h-122rpx bg-hex-FFFFFF px-32rpx">
          <div class="mb-20rpx h-2rpx w-full bg-hex-F5F5F5" />
          <div class="h-102rpx flex items-center justify-between">
            <div class="text-24rpx text-hex-7C8699"><text class="text-hex-C4C4C4">{{ dynamicContent.length }}</text>/120</div>
            <div class="flex items-center">
              <div class="mr-32rpx text-28rpx text-hex-ABCD03" @click="goadd('1', '1')">存草稿</div>
              <div class="btn-theme-bg h-62rpx min-w-140rpx b rounded-12rpx text-center text-28rpx leading-62rpx text-hex-fff"
                   @click="goadd('1', '0')">发布</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 写文章 -->
    <div v-if="tabindex==='1' && secondindex ==='1'">
      <div class="100vh box-border px-32rpx">
        <div class="wealth-text w-full bg-hex-F5F5F5">
          <input v-model="articleTitle" maxlength="30" type="text" class="h-100rpx w-full bg-hex-fff text-36rpx" placeholder="请输入标题(限5-30字)">
          <qqyEditor
            ref="editorRef"
            :height="`${keyboardHeight > 0 ? `calc(100vh - ${topHeight + toolTopKeyHeight+100}px)` : `calc(100vh - ${topHeight+othorHeight+45}px)`}` "
            :placeholder="placeholder"
            @init="editorInit"
            @oncurLength="onHtmlChang" />
          <!-- 键盘弹出 -->
          <div v-if="keyboardHeight>0" class="fixed bottom-0px left-0 right-0 z-9999 border-t-2rpx border-hex-f5f5f5 border-solid" :style="{ bottom: `${toolTopKeyHeight}px` }">
            <div class="h-100rpx w-100% flex items-center bg-hex-fff px-32rpx leading-100rpx">
              <image :src="`${cdnUrl}/svgicons/inputimg.svg${imgVersion}`" class="w-50rpx" mode="widthFix" @click="articleSelect" />
            </div>
          </div>
        </div>
        <div v-if="keyboardHeight===0">
          <div class="tablist fixed bottom-200rpx left-0 right-0 z-99 h-102rpx bg-hex-FFFFFF px-32rpx" :class="{ 'bottom-520rpx': isShowColumn }">
            <div class="mb-24rpx flex items-center justify-between text-28rpx text-hex-7C8699" @click="handleShowColumn">
              <div>{{ columnName }}</div>
              <uni-icons :type="isShowColumn?'top':'bottom'" size="16" />
            </div>
            <div v-if="isShowColumn" class="columns mb-32rpx box-border max-h-350rpx overflow-y-auto rounded-30rpx bg-hex-F6F6F6 p-32rpx">
              <div v-for="item in categoryList" class="mb-32rpx text-28rpx text-hex-7c8699"
                   :class="columnName===item.name ? 'text-hex-000000 font-700 text-34rpx':''"
                   @click="changecolumnId(item)">{{ item.name }}</div>
            </div>
          </div>
          <div class="operate fixed bottom-30rpx left-0 right-0 z-99 h-192rpx bg-hex-FFFFFF px-32rpx">
            <div class="h-2rpx w-full bg-hex-F5F5F5" />
            <div class="h-90rpx flex items-center">
              <image :src="`${cdnUrl}/svgicons/inputimg.svg${imgVersion}`" class="w-50rpx" mode="widthFix" @click="articleSelect" />
            </div>
            <div class="h-102rpx flex items-center justify-between">
              <div class="text-24rpx text-hex-7C8699"><text class="text-hex-C4C4C4">{{ articleTextNumber }}</text>/500</div>
              <div class="flex items-center">
                <div class="mr-32rpx text-28rpx text-hex-ABCD03" @click="goadd('2', '1')">存草稿</div>
                <div class="btn-theme-bg h-62rpx min-w-140rpx rounded-12rpx text-center text-28rpx leading-62rpx"
                     @click="gonext">下一步</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 传视频 -->
    <div v-if="tabindex==='2'">
      <div class="box-border px-32rpx pb-370rpx">
        <x-video v-if="fileLists.length > 0" videoId="myVideo" class="w-full rounded-32rpx" :src="fileLists[0]" :progress="0.1" />
        <!--  <video v-if="fileLists.length > 0" id="myVideo" class="mb-54rpx w-full rounded-32rpx"
               :src="fileLists[0]"
               controls /> -->
        <div v-if="fileLists.length === 0" class="mb-20rpx h-152rpx w-152rpx flex flex-col items-center justify-center bg-hex-F5F5F5" @click="selectvideo">
          <uni-icons type="plusempty" size="30" color="#D9D9D9" />
        </div>
        <input v-model="videoTitle" type="text" class="mb-25rpx w-full text-36rpx" placeholder="请输入标题(限5-30字)">
        <div class="mb-25rpx mb-40rpx h-2rpx w-full bg-hex-F5F5F5" />
        <div class="max-h-600rpx overflow-y-scroll">
          <uni-easyinput v-model="videocContent" :inputBorder="false" maxlength="500"
                         autoHeight type="textarea"
                         placeholderStyle="color:#C4C4C4;font-size:32rpx"
                         placeholder="请输入正文(限500字)" />
        </div>
        <div class="tablist fixed bottom-200rpx left-0 right-0 z-99 h-102rpx bg-hex-FFFFFF px-32rpx" :class="{ 'bottom-520rpx': isShowColumn }">
          <div class="mb-24rpx flex items-center justify-between text-28rpx text-hex-7C8699" @click="handleShowColumn">
            <div>{{ columnName }}</div>
            <uni-icons :type="isShowColumn?'top':'bottom'" size="16" />
          </div>
          <div v-if="isShowColumn" class="columns mb-32rpx box-border max-h-350rpx overflow-y-auto rounded-30rpx bg-hex-F6F6F6 p-32rpx">
            <div v-for="item in categoryList" class="mb-32rpx text-28rpx text-hex-7c8699"
                 :class="columnName===item.name ? 'text-hex-000000 font-700 text-34rpx':''"
                 @click="changecolumnId(item)">{{ item.name }}</div>
          </div>
        </div>
        <div class="fixed bottom-30rpx left-0 right-0 z-99 h-122rpx bg-hex-FFFFFF px-32rpx">
          <div class="mb-20rpx h-2rpx w-full bg-hex-F5F5F5" />
          <div class="h-102rpx flex items-center justify-between">
            <div class="text-24rpx text-hex-7C8699"><text class="text-hex-C4C4C4">{{ videocContent.length }}</text>/{{ articleMaxNum }}</div>
            <div class="flex items-center">
              <div class="mr-32rpx text-28rpx text-hex-ABCD03" @click="goadd('3', '1')">存草稿</div>
              <div class="btn-theme-bg h-62rpx min-w-140rpx rounded-12rpx text-center text-28rpx leading-62rpx text-hex-fff"
                   @click="goadd('3', '0')">发布</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 上传封面 -->
    <div v-if="tabindex==='1' && secondindex ==='2'">
      <div class="box-border px-32rpx pb-370rpx">
        <div class="w-50% overflow-hidden rounded-32rpx shadow">
          <div class="relative min-h-286rpx flex flex-col items-center justify-center bg-hex-F5F5F5" @click="firstSelect">
            <div v-if="coverImg" class="relative h-286rpx w-100% overflow-hidden">
              <image
                class="absolute left-50% top-50% h-286rpx w-100% rounded-16rpx"
                style="transform: translate(-50%, -50%);"
                :src="coverImg"
                mode="aspectFill"
              />
            </div>
            <div class="absolute top-0 h-286rpx w-full flex flex-col items-center justify-center bg-[rgba(245,245,245,0.5)]">
              <uni-icons type="plusempty" size="48" color="#666" />
              <div class="mt-24rpx text-38rpx font-600 text-hex-666">上传封面</div>
            </div>
          </div>
          <div class="box-border p-24rpx">
            <div class="multiLine-hiddle mb-24rpx">{{ articleTitle }}</div>
            <div class="flex items-center justify-between">
              <div class="flex items-center justify-between">
                <image
                  class="mr-12rpx h-44rpx w-44rpx"
                  :src="avatarUrl"
                  mode="scaleToFill"
                />
                <text class="text-24rpx text-hex-7C8699">{{ nickName }}</text>
              </div>
              <div class="mr-13rpx text-60rpx text-hex-ABAFB5">
                <image :src="`${cdnUrl}/imgs/square/more.png${imgVersion}`" mode="widthFix" class="w-44rpx" />
              </div>
            </div>
          </div>
        </div>
        <div class="fixed bottom-30rpx left-0 right-0 h-102rpx bg-hex-FFFFFF px-32rpx">
          <div class="h-102rpx flex items-center justify-between">
            <div class="text-28rpx text-hex-7C8699" />
            <div class="flex items-center">
              <div class="mr-32rpx text-28rpx text-hex-ABCD03" @click="goadd('2', '1')">存草稿</div>
              <div class="btn-theme-bg h-62rpx min-w-140rpx rounded-12rpx text-center text-28rpx leading-62rpx text-hex-fff"
                   @click="goadd('2', '0')">发布</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div v-if="isShowPreview">
      <q-preview-image :urls="showImgsList" :current-index="currentIndexPre" :isShowDownLoad="false"
                       @close="closePreview" />
    </div>
  </div>
</template>

<script setup lang="ts">
let searchBarTop: any = $ref('24')
onLoad(() => {
  // #ifndef H5
  let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
  searchBarTop = menuButtonInfo.top
  // #endif
})
let articleId: any = $ref('')
let articleType: any = $ref() //文章详情的类型
onLoad((options) => {
  if (options) {
    articleType = options.articleType
    articleId = options.articleId
  }
})
let topHeight = $ref(0)
let othorHeight = $ref(0)
//键盘高度
let keyboardHeight = $ref(0)
const updatePosition = (height) => {
  keyboardHeight = height
}
let devive = $ref('')
const getDeviveType = async () => {
  devive = await checkDeviceType()
}
const toolTopKeyHeight = $computed(() => {
  return devive === 'iOS' ? keyboardHeight : 0
})
watch(() => keyboardHeight, () => {
  getDeviveType()
})
let editorRef: any = $ref(null)

const placeholder: any = $computed(() => {
  return articleTextNumber === 0 && '请输入正文(限500字)'
})

//监听富文本输入的内容统计字数
const onHtmlChang = (conut: number) => {
  articleTextNumber = conut
  if (conut > 500) {
    uni.showToast({
      title: '超过字数',
      icon: 'none',
      mask: false,
    })
  }
}
//获取富文本内容
const getEditorHtml = () => {
  return new Promise((resolve, reject) => {
    editorRef.editorCtx.getContents({
      success: (res) => {
        function traverse() {
          let imgIndex = 0
          let result: any = []
          res.delta.ops.forEach((item) => {
            if (typeof item.insert === 'string') {
              result.push({ type: 'text', content: item.insert })
            } else {
              result.push({ type: 'img', content: item.insert.image, index: imgIndex })
              imgIndex++
            }
          })
          return result
        }
        const contenJson = traverse()
        resolve(contenJson)
      },
      fail: (error) => {
        reject(error)
      },
    })
  })
}

//富文本上传
const uplodImg = (fileUrl: string) => {
  editorRef.editorCtx.insertImage({
    src: fileUrl,
    success: (res) => {
      editorRef.editorCtx.insertText({ text: '\n' + '\n' })
    },
  })
}
// 发动态预览
let showImgsList: any = $ref([])
let isShowPreview: any = $ref(false)
let currentIndexPre: any = $ref(1) //预览图片位置
const previewImage = (index) => { // index 索引 如果 需要复用方法 可以使用 类型来进行区分(val)
  currentIndexPre = index
  isShowPreview = true
}
const closePreview = () => {
  isShowPreview = false
}
// 获取类目列表数据
let categoryList: any = $ref([])
const getcategoryList = async () => {
  const { status, data } = await Fetch('/api/s/square/columnList')
  if (status !== 200 || data.code !== 0) {
    return
  }
  categoryList = data.result.dataList
  categoryList.splice(0, 1)
}
// 发动态--------------------------
let fileLists: any = $ref([])
const select = async () => {
  await chooseImage({
    count: 3, //
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], //从相册选择
    async success(res: any) {
      for (let i = 0; i < res.tempFiles.length; i++) {
        const fileUrl = await uploadCosFile(res.tempFiles[i], res.tempFiles[i].path)
        fileLists.push(fileUrl)
        showImgsList = fileLists
      }
    },
    async fail(res: any) {
      uni.showToast({
        title: '上传失败，请重新上传',
        icon: 'error',
      })
    },
  })
}
const deleteImg = (index) => {
  fileLists.splice(index, 1)
}
// 发动态的文本
let dynamicContent: any = $ref('')
let tabindex: any = $ref()
// 控制下一步的页面
let secondindex: any = $ref('1')
// 类目id
let isShowColumn = $ref(false)
let columnName = $ref('栏目选择')
let columnId: any = $ref(2)
const handleShowColumn = () => {
  isShowColumn = !isShowColumn
}
const changecolumnId = (item) => {
  columnId = item.id
  columnName = item.name
  isShowColumn = false
}
// 发文章----------------------
let articleTitle: any = $ref('')
let articlecontent: any = $ref('')
let articleList: any = $ref([])
let articleTextNumber: any = $ref(0)//文章输入字符的长度
const articleMaxNum: any = $ref(500)
let maxLength: any = $ref('500')
let articleFocus: any = $ref(false)
// 封面图片
let coverImg: any = $ref('')
// 失焦事件
const onBlur = () => {
  if (!articlecontent) {
    return
  }
  articleList.push({ type: 'text', content: articlecontent })
  let textList: any = []
  textList = articleList.filter((item) => {
    return item.type === 'text'
  })
  if (textList.length > 1) {
    articleTextNumber = 0
    textList.forEach((item: any) => {
      articleTextNumber += item.content.length
      maxLength = Number(articleMaxNum) - Number(articleTextNumber)
    })
    if (Number(articleTextNumber) > 500) {
      articleTextNumber = 500
    }
  } else {
    articleTextNumber = Number(textList[0].content.length)
    maxLength = Number(articleMaxNum) - Number(articleTextNumber)
  }
  upUserInputTextLength = 0
  articlecontent = ''
  // articlePlaceholder = ''
  articleFocus = true
}
let curIndex = $ref(0)
const getIndex = (index) => {
  curIndex = index
}
// 已经写好的文章输入事件
const articleUpdateInput = () => {
  let textList: any = []
  textList = articleList.filter((item) => {
    return item.type === 'text'
  })
  if (textList.length > 1) {
    articleTextNumber = 0
    textList.forEach((item: any) => {
      articleTextNumber += item.content.length
      maxLength = Number(articleMaxNum) - Number(articleTextNumber)
    })
    if (Number(articleTextNumber) > 500) {
      articleTextNumber = 500
      uni.showToast({
        title: '超过字数',
        icon: 'none',
        mask: false,
      })
    }
  } else {
    articleTextNumber = Number(textList[0].content.length)
    maxLength = Number(articleMaxNum) - Number(articleTextNumber)
  }
  upUserInputTextLength = 0
}
let currentIndex = $ref(0)
const articleSelect = async () => {
  await chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], //从相册选择
    async success(res: any) {
      for (let i = 0; i < res.tempFiles.length; i++) {
        const fileUrl = await uploadCosFile(res.tempFiles[i], res.tempFiles[i].path)
        fileLists.push(fileUrl)
        articleList.push({ type: 'img', index: currentIndex, content: fileUrl })
        uplodImg(fileUrl)
      }
      let textList = []
      textList = articleList.filter((item) => {
        return item.type === 'img'
      })
      showImgsList = []
      textList.forEach((item: any) => {
        showImgsList.push(item.content)
      })
      currentIndex++
    },
    async fail(res: any) {
      uni.showToast({
        title: '上传失败，请重新上传',
        icon: 'error',
      })
    },
  })
}
const articlePlaceholder = $computed(() => {
  return articleList[0]?.content.length ? '' : '请输入正文(限500字)'
})
const deleteArticleImg = (index) => {
  articleList.splice(index, 1)
  if (articleList[index - 1].type === 'text') {
    articleList[index - 1].isFocus = true
  }
}
let upUserInputTextLength: any = $ref(0)//用户上一次输入的长度
const articleInput = (event) => {
  articleTextNumber = Number(articleTextNumber) - Number(upUserInputTextLength) + Number(event.length)
  upUserInputTextLength = event.length
  if (event.length === 0) {
    console.log(articleList[articleList.length - 1], '-------------')
    if (articleList[articleList.length - 1].type === 'text') {
      articleList[articleList.length - 1].isFocus = true
    }
  }
}
const editorInit = () => {
  editorRef.editorCtx.setContents({
    html: parseDOM(articleList),
  })
}
// 发文章----------------------
onMounted(() => {
  tabindex = articleType

  // uni.showModal({ title: '上传失败', content: '333333333', showCancel: true })
  getcategoryList()
  getArticleDetail(articleId)
  uni.onKeyboardHeightChange((res: any) => {
    if (res.height === keyboardHeight) return
    keyboardHeight = res.height
    const duration = res.height > 0 ? res.duration * 1000 : 0
    keyboardHeight = res.height
    setTimeout(() => {
      uni.pageScrollTo({
        scrollTop: 0,
        success: () => {
          updatePosition(keyboardHeight)
          editorRef.editorCtx.scrollIntoView() //使得编辑器光标处滚动到窗口可视区域内
        },
      })
    }, duration)
  })
  nextTick(() => {
    uni.createSelectorQuery().select('.wealth-text').boundingClientRect((rect: any) => {
      topHeight = rect?.top
    }).exec()
    uni.createSelectorQuery().selectAll('.operate, .tablist').boundingClientRect((rect: any) => {
      othorHeight = rect.reduce((sum, obj) => sum + obj.height, 0)
    }).exec()
  })
})
let avatarUrl = $ref('')
let nickName = $ref('')
const getArticleDetail = async (articleId) => {
  if (isNilOrEmpty(articleId)) {
    return
  }
  const reqData = {
    method: 'post',
    headers: { timestamp: new Date().getTime() },
    data: { user_article__id: articleId },
  }
  const { data, status, error } = await Fetch('/api/s/publish/draftDetail', reqData)
  if (status !== 200 || data.code !== 0) {
    return
  }
  const queryData = data.result.dataList[0]
  switch (articleType) {
    case '0':
      fileLists = queryData.multi_media.split(',')
      showImgsList = fileLists
      dynamicContent = queryData.content
      columnId = queryData.column_id
      columnName = queryData.name
      break
    case '1':
      fileLists = queryData.multi_media.split(',')
      showImgsList = fileLists
      articleTitle = queryData.title
      articleList = JSON.parse(queryData.content)
      columnId = queryData.column_id
      columnName = queryData.name
      avatarUrl = queryData.avatar_url
      nickName = queryData.nickname
      coverImg = queryData.cover_image
      articleUpdateInput()
      break
    case '2':
      fileLists = queryData.multi_media.split(',')
      videoTitle = queryData.title
      videocContent = queryData.content
      columnId = queryData.column_id
      columnName = queryData.name
      break
    default:
      break
  }
}
// 写文章下一步
const gonext = async () => {
  if (articleTextNumber === 0 || articleTitle === '') {
    uni.showToast({
      title: '文章标题及内容不能为空',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  if (articleTitle.length < 5) {
    uni.showToast({
      title: '标题长度需在5至30位之间',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  const dataList: any = await getEditorHtml()
  let listImage = dataList.filter(item => item.type === 'img')
  if (listImage.length === 0 || fileLists.length === 0) {
    articleList = []
    uni.showToast({ title: '请上传图片', icon: 'none', duration: 2000 })
    return
  }
  if (articleTextNumber > 500) {
    uni.showToast({
      title: '超过字数',
      icon: 'none',
      mask: false,
    })
    return
  }
  secondindex = '2'
}
//上传文章封面
const firstSelect = async () => {
  await chooseImage({
    count: 1, //默认9
    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
    sourceType: ['album', 'camera'], //从相册选择
    async success(res: any) {
      for (let i = 0; i < res.tempFiles.length; i++) {
        const fileUrl = await uploadCosFile(res.tempFiles[i], res.tempFiles[i].path)
        coverImg = fileUrl
      }
    },
    async fail(res: any) {
      uni.showToast({
        title: '上传失败，请重新上传',
        icon: 'error',
      })
    },
  })
}
const goBack = () => {
  uni.navigateBack({
    delta: 1,
  })
}
// 发视频----------------------------
let videocContent: any = $ref('')
let videoTitle: any = $ref('')
let videocover: any = $ref('')
const selectvideo = async () => {
  await chooseVideo({
    async success(res: any) {
      const fileUrl = await uploadCosFile(res.tempFile, res.tempFilePath)
      fileLists.push(fileUrl)
    },
    async fail(res: any) {
      uni.showToast({
        title: '上传失败，请重新上传',
        icon: 'error',
      })
    },
  })
}
// 发布
const addArticle = async (articleType, columnId, content, coverImage, isDraft, multiMedia, title) => {
  if (!content) {
    uni.showToast({
      title: '上传的文字不能为空',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  if (!multiMedia) {
    uni.showToast({
      title: '请上传图片',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  uni.showLoading({
    title: '保存中',
    mask: false,
  })
  const reqData = {
    method: 'post',
    data: {
      'articleType': articleType,
      'columnId': columnId,
      'content': content,
      'coverImage': coverImage,
      'isDraft': isDraft,
      'multiMedia': multiMedia,
      'title': title,
    },
  }
  const { data, status } = await Fetch('/qqyapi/auth/article/addArticle', reqData)
  if (data.code === 0) {
    currentIndex = 0
    setTimeout(() => {
      if (isDraft === '1') {
        uni.hideLoading()
        uni.navigateTo({
          url: '/pages-square/drafts',
        })
      } else {
        uni.hideLoading()
        uni.reLaunch({
          url: '/pages/square',
        })
      }
    }, 1600)
  }
}
// 更新草稿
const updateArticle = async (id, articleType, columnId, content, coverImage, isDraft, multiMedia, title) => {
  if (!content) {
    uni.showToast({
      title: '上传的文字不能为空',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  if (!multiMedia) {
    uni.showToast({
      title: '请上传图片',
      icon: 'none',
      duration: 2000,
    })
    return
  }
  uni.showLoading({
    title: '保存中',
    mask: true,
  })
  const reqData = {
    method: 'post',
    data: {
      'id': id,
      'articleType': articleType,
      'columnId': columnId,
      'content': content,
      'coverImage': coverImage,
      'isDraft': isDraft,
      'multiMedia': multiMedia,
      'title': title,
    },
  }
  const { data, status } = await Fetch('/qqyapi/auth/article/updateArticle', reqData)
  if (data.code === 0) {
    currentIndex = 0
    setTimeout(() => {
      if (isDraft === '1') {
        uni.hideLoading()
        uni.navigateTo({
          url: '/pages-square/drafts',
        })
      } else {
        uni.hideLoading()
        uni.reLaunch({
          url: '/pages/square',
        })
      }
    }, 1600)
  }
}
// 点击发布的事件 1发动态  2发文章   3传视频
const goadd = useThrottleFn(async (type, draft) => {
  let jsonArticleList = type === '2' && JSON.stringify(await getEditorHtml())
  switch (type) {
    case '1':
      if (!draft) {
        addArticle('0', columnId, dynamicContent, fileLists[0], draft, fileLists.join(','), '动态无标题')
      } else {
        updateArticle(articleId, '0', columnId, dynamicContent, fileLists[0], draft, fileLists.join(','), '动态无标题')
      }
      // dynamicContent = ''
      // fileLists = []
      break
    case '2':
      if (!coverImg) {
        coverImg = fileLists[0]
      }
      if (!draft) {
        addArticle('1', columnId, jsonArticleList, coverImg, draft, fileLists.join(','), articleTitle)
      } else {
        updateArticle(articleId, '1', columnId, jsonArticleList, coverImg, draft, fileLists.join(','), articleTitle)
      }
      // articlecontent = ''
      // coverImg = ''
      // fileLists = []
      // articleTitle = ''
      // articleList = []
      break
    case '3':
      videocover = await getvideoimg(fileLists[0])
      if (videoTitle.length < 5) {
        uni.showToast({
          title: '标题长度需在5至30位之间',
          icon: 'none',
          duration: 2000,
        })
        return
      }
      if (!draft) {
        addArticle('2', columnId, videocContent, formatVidelUrl + videocover, draft, fileLists.join(','), videoTitle)
      } else {
        updateArticle(articleId, '2', columnId, videocContent, formatVidelUrl + videocover, draft, fileLists.join(','), videoTitle)
      }
      // videocContent = ''
      // fileLists = []
      // videoTitle = ''
      break
    default:
      break
  }
}, 1000)
let formatVidelUrl = 'https://qqy-1254346585.cos.ap-nanjing.myqcloud.com/'
const getvideoimg = async (url) => {
  if (!url) {
    return
  }
  const formatUrl = url.replace(formatVidelUrl, '')
  const reqData = {
    method: 'post',
    data: {
      'videoPath': formatUrl,
    },
  }
  const { data, status } = await Fetch('/qqyapi/auth/oss/videoShotImage', reqData)
  const videlImg = data?.data
  return videlImg
}
</script>

<route lang="json">
{"style":{"disableScroll":true}}
</route>

<style lang="scss">
.edit-draft{
  .multiLine-hiddle{
    overflow : hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
  }

  .triangle{
    width: 0;
    height: 0;
    border-color: transparent #fff; /* 上下颜色 左右颜色 */
    border-width: 0 0 24rpx 24rpx;
    border-style: solid;
  }

  ::v-deep(.uni-textarea-wrapper)  {
    .uni-textarea-wrapper{
      font-size: 32rpx !important;
      color: #7C8699,
    }
  }

  .container {
    box-sizing: border-box;
    border-top: 1px solid #f5f5f5;
    background-color: #fff;
    width: 100%;
    height: 100%;
    font-size: 28rpx;
    line-height: 1.5;
    overflow: auto;
    padding-bottom: 40rpx;
    min-height: unset !important;
  }

  .ql-editor.ql-blank::before {
    color: #C4C4C4 ;
    font-style: normal;
    font-size: 28rpx;
  }
}
</style>
